package com.example.tliaswebmanagement.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.tliaswebmanagement.pojo.Result;
import com.example.tliaswebmanagement.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求url
        String url = request.getRequestURL().toString();
        log.info("拦截到请求：{}", url);
        //2、判断请求url是否包含login，如果包含，放行
        if (url.contains("login")) {
            log.info("登录页面，放行...");
            return true;
        }
        //3、获取请求头中（token）的jwt令牌
        String jwt = request.getHeader("token");
        //4、判断jwt是否为空，如果为空，拦截，否则放行
        if (!StringUtils.hasLength(jwt)) {
            log.info("无token，拦截...");
            Result error = Result.error("NOT_LOGIN");
            //手动转换对象-->json 阿里巴巴
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        //5、解析token如果解析失败，返回错误结果（未登录）
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析token失败，拦截...");
            Result error = Result.error("NOT_LOGIN");
            //手动转换对象-->json 阿里巴巴
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        //没问题放行
        log.info("令牌合法，放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
